package cn.sinokj.party.chineseFourParty.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.sdk.WebSettings.PluginState;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.apache.http.cookie.Cookie;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.ShowWebImageActivity;
import cn.sinokj.party.chineseFourParty.fragment.base.BaseFragment;
import cn.sinokj.party.chineseFourParty.utils.http.MyHttpClient;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmDialog;
import cn.sinokj.party.chineseFourParty.view.webview.X5WebView;


/**
 * Description
 *
 * @author azzbcc on 16-10-31 上午9:59
 * @email azzbcc@sina.com
 */
public class WebFragment extends BaseFragment {
    private X5WebView webView;

    private CookieManager cookieManager;
    private View mErrorView;
    //---------
    private FrameLayout mLayout;
    private View nVideoView = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getActivity().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                        WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
            logger.e(e);
        }
        CookieSyncManager.createInstance(getActivity());
        cookieManager = CookieManager.getInstance();
        cookieManager.removeSessionCookie();
        cookieManager.removeAllCookie();
        cookieManager.setAcceptCookie(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.web_fragment, container, false);
        webView = (X5WebView) view.findViewById(R.id.web_fragment_view);
        mLayout = (FrameLayout) view.findViewById(R.id.fl_video);
        initializeWebView();
        return view;
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initializeWebView() {
        WebSettings settings = webView.getSettings();

        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setAppCacheMaxSize(Long.MAX_VALUE);
        settings.setAppCachePath(getActivity().getDir("appcache", 0).getPath());
        settings.setDatabasePath(getActivity().getDir("databases", 0).getPath());
        settings.setGeolocationDatabasePath(getActivity().getDir("geolocation", 0).getPath());
        // 设置支持Javascript
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设定支持viewport
        settings.setUseWideViewPort(true);
        //      是否调节内容 是否全屏
        settings.setLoadWithOverviewMode(true);
        settings.setTextZoom(100);
        settings.setSupportMultipleWindows(false);
        // 设置此属性，可任意比例缩放
        settings.setSupportZoom(true);
        // 便页面支持缩放：
        settings.setBuiltInZoomControls(true);
        //不显示webview缩放按钮
        settings.setDisplayZoomControls(false);
        // 设置本地文件访问
        settings.setAllowFileAccess(true);
        // 支持视频播放
        settings.setPluginsEnabled(true);
        settings.setPluginState(PluginState.ON_DEMAND);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 图片自适应
        settings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        //设置渲染优先级
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 指定的垂直滚动条有叠加样式
        webView.setVerticalScrollbarOverlay(true);
        // 如果webView中需要用户手动输入用户名、密码或其他，则webview必须设置支持获取手势焦点。
        webView.requestFocusFromTouch();
        // 网页alert拦截
        webView.setWebChromeClient(new WebChromeClient() {
            private IX5WebChromeClient.CustomViewCallback customViewCallback;

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                ConfirmDialog.confirmAction(view.getContext(), message, "确定", null, null);
                result.confirm();// 因为没有绑定事件，需要强行confirm,否则页面会变黑显示不了内容。
                return true;
            }

            @Override
            public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
                super.onShowCustomView(view, callback);
                if (nVideoView != null) {
                    callback.onCustomViewHidden();
                    return;
                }
                nVideoView = view;
                nVideoView.setVisibility(View.VISIBLE);
                customViewCallback = callback;
                mLayout.addView(nVideoView);
                mLayout.setVisibility(View.VISIBLE);
                mLayout.bringToFront();
                //设置横屏
                //getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                //设置全屏
                // getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }

            // 退出全屏调用此函数
            @Override
            public void onHideCustomView() {
                if (nVideoView == null) {
                    return;
                }
                try {
                    customViewCallback.onCustomViewHidden();
                } catch (Exception e) {
                }
                nVideoView.setVisibility(View.GONE);
                mLayout.removeView(nVideoView);
                nVideoView = null;
                mLayout.setVisibility(View.GONE);
                // 设置竖屏
                //getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                // 取消全屏
                // final WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
                // attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                // getActivity().getWindow().setAttributes(attrs);
                // getActivity(). getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.addJavascriptInterface(new JavascriptInterface(getActivity()), "imagelistner");
        // 打开网页时不调用系统浏览器， 而是在本WebView中显示
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (getActivity() == null) {
                    return super.shouldOverrideUrlLoading(view, url);
                }
                // 获取上下文, H5PayDemoActivity为当前页面
                final Activity context = getActivity();

                // ------  对alipays:相关的scheme处理 -------
                if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(context)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        context.startActivity(new Intent("android.intent.action.VIEW",
                                                alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                }

                // 如下方案可在非微信内部WebView的H5页面中调出微信支付
                if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                DialogShow.closeDialog();
                if(url.startsWith("http://djy.ewanyuan.cn/shopapp/")||url.startsWith("https://djy.ewanyuan.cn/shopapp/")){
                    return;
                }
                addImageClickListner();
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                setCookie(url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                DialogShow.showRoundProcessDialog(getActivity());
            }

                                     @Override
                                     public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
                                         sslErrorHandler.proceed();// 接受所有网站的证书
                                     }

                                     @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(webView, webResourceRequest, webResourceError);
                CharSequence description = webResourceError.getDescription();
                if (!TextUtils.equals("net::ERR_NAME_NOT_RESOLVED", description)) {
                    showErrorPage();
                }
            }
        }

        );
        webView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                        long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

    }

    protected void showErrorPage() {
        LinearLayout webParentView = (LinearLayout) webView.getParent();
        initErrorPage();//初始化自定义页面
        while (webParentView.getChildCount() > 1) {
            webParentView.removeViewAt(0);
        }
        @SuppressWarnings("deprecation")
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewPager.LayoutParams.FILL_PARENT, ViewPager.LayoutParams.FILL_PARENT);
        webParentView.addView(mErrorView, 0, lp);
    }

    /**
     * 显示加载失败时自定义的网页
     */
    protected void initErrorPage() {
        if (mErrorView == null) {
            mErrorView = View.inflate(getActivity(), R.layout.webview_error, null);
            mErrorView.setOnClickListener(null);
        }
    }

    private boolean isUrl(String url) {
        String matches = "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";
        if (TextUtils.isEmpty(url))
            return false;
        return url.matches(matches);
    }

    public void loadUrl(String url) {
        setCookie(url);
        webView.loadUrl(url);
    }

    public void loadDataWithBaseURL(String baseUrl, String data, String historyUrl) {
        webView.loadDataWithBaseURL(baseUrl, data, "text/html", "UTF-8", historyUrl);
    }

    private void setCookie(String url) {
        if (isUrl(url)) {
            // 同步所有的Cookie到webview中
            List<Cookie> cookieList = MyHttpClient.getCookie();

            for (Cookie cookie : cookieList) {
                String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain()
                        + "; path=/";
                cookieManager.setCookie(url, cookieString);
                CookieSyncManager.getInstance().sync();
            }
        }
    }

    public WebView getWebView() {
        return webView;
    }

    // 注入js函数监听
    private void addImageClickListner() {
        //遍历页面中所有img的节点，因为节点里面的图片的url即objs[i].src，保存所有图片的src.为每个图片设置点击事件，objs[i].onclick
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{" +
                "window.imagelistner.readImageUrl(objs[i].src);  " +
                " objs[i].onclick=function()  " +
                " {  " +
                " window.imagelistner.openImage(this.src);  " +
                "  }  " +
                "}" +
                "})()");
    }

    // js通信接口
    List<String> images = new ArrayList<>();

    public class JavascriptInterface {
        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }

        @android.webkit.JavascriptInterface
        public void readImageUrl(String img) {     //把所有图片的url保存在ArrayList<String>中
            images.add(img);
        }

        @android.webkit.JavascriptInterface
        public void openImage(String clickimg) {
            ArrayList<String> list = addImages();
            String[] imageUrls = list.toArray(new String[list.size()]);
            Intent intent = new Intent(getActivity(), ShowWebImageActivity.class);
            intent.putExtra("imageUrls", imageUrls);
            intent.putExtra("curImageUrl", clickimg);
            getActivity().startActivity(intent);
        }
    }

    //去重复
    private ArrayList<String> addImages() {
        ArrayList<String> list = new ArrayList<>();
        Set set = new HashSet();
        for (String cd : images) {
            if (set.add(cd)) {
                list.add(cd);
            }
        }
        return list;
    }

    @Override
    public void onDestroy() {
        // 返回后仍有声音
        ViewGroup viewGroup = (ViewGroup) webView.getParent();
        viewGroup.removeView(webView);
        webView.destroy();
        super.onDestroy();
    }
}
